package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"gozerogateway/rpc/model/svcmodel"

	"gozerogateway/rpc/svc/internal/svc"
	"gozerogateway/rpc/svc/svcclient"

	"encoding/json"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ServiceUpdateHttpLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewServiceUpdateHttpLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServiceUpdateHttpLogic {
	return &ServiceUpdateHttpLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ServiceUpdateHttpLogic) ServiceUpdateHttp(in *svcclient.ServiceUpdateHttpReq) (*svcclient.ServiceUpdateHttpResp, error) {
	// todo: add your logic here and delete this line
	serviceinfo, err := l.svcCtx.SvcModel.FindOneByServiceNameAntReturn(l.ctx, in.ServiceName)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_name查询info表信息失败,this http service is not exist,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}
	ServiceId := serviceinfo.Id

	_, err = l.svcCtx.SvcHttpModel.FindOne(l.ctx, ServiceId)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_id查询http表信息失败,,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	_, err = l.svcCtx.SvcAccessControlModel.FindOne(l.ctx, ServiceId)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_id查询accesscontrol表信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	_, err = l.svcCtx.SvcLoadBalanceModel.FindOne(l.ctx, ServiceId)
	if err != nil {
		reqStr, _ := json.Marshal(in)
		logx.WithContext(l.ctx).Errorf("根据service_id查询loadbalance表信息失败,参数:%s,异常:%s", reqStr, err.Error())
		return nil, err
	}

	if errtrans := l.svcCtx.SvcHttpModel.TransCtx(l.ctx, func(ctx context.Context, session sqlx.Session) error {
		_, err = l.svcCtx.SvcHttpModel.FindOne(l.ctx, ServiceId)

		if errUpdateHttpTable0 := l.svcCtx.SvcModel.TransUpdate(l.ctx, session, &svcmodel.GatewayServiceInfo{
			ServiceName: in.ServiceName,
			ServiceDesc: in.ServiceDesc,
		}); errUpdateHttpTable0 != nil {

		}

		if errUpdateHttpTable1 := l.svcCtx.SvcLoadBalanceModel.TransUpdate(l.ctx, session, &svcmodel.GatewayServiceLoadBalance{
			ServiceId:              ServiceId,
			RoundType:              in.RoundType,
			IpList:                 in.IpList,
			WeightList:             in.WeightList,
			UpstreamConnectTimeout: in.UpstreamConnectTimeout,
			UpstreamHeaderTimeout:  in.UpstreamHeaderTimeout,
			UpstreamIdleTimeout:    in.UpstreamIdleTimeout,
			UpstreamMaxIdle:        in.UpstreamMaxIdle,
		}); errUpdateHttpTable1 != nil {
			return errUpdateHttpTable1
		}
		if errUpdateHttpTable2 := l.svcCtx.SvcAccessControlModel.TransUpdate(l.ctx, session, &svcmodel.GatewayServiceAccessControl{
			ServiceId:         ServiceId,
			OpenAuth:          in.OpenAuth,
			BlackList:         in.BlackList,
			WhiteList:         in.WhiteList,
			ClientipFlowLimit: in.ClientipFlowLimit,
			ServiceFlowLimit:  in.ServiceFlowLimit,
		}); errUpdateHttpTable2 != nil {
			return errUpdateHttpTable2
		}
		if errUpdateHttpTable3 := l.svcCtx.SvcHttpModel.TransUpdate(l.ctx, session, &svcmodel.GatewayServiceHttpRule{
			ServiceId:      ServiceId,
			NeedHttps:      in.NeedHttps,
			NeedStripUri:   in.NeedStripUri,
			NeedWebsocket:  in.NeedWebsocket,
			UrlRewrite:     in.UrlRewrite,
			HeaderTransfor: in.HeaderTransfor,
		}); errUpdateHttpTable3 != nil {
			return errUpdateHttpTable3
		}

		return nil
	}); errtrans != nil {
		return nil, errors.New("trans update http table error")
	}
	//tcpDo, err := l.svcCtx.SvcTcpModel.FindOne(l.ctx, ServiceId)
	//if err != nil {
	//	reqStr, _ := json.Marshal(in)
	//	logx.WithContext(l.ctx).Errorf("根据service_id查询tcp表信息失败,参数:%s,异常:%s", reqStr, err.Error())
	//	return nil, err
	//}
	//
	//grpcDo, err := l.svcCtx.SvcGrpcModel.FindOne(l.ctx, ServiceId)
	//if err != nil {
	//	reqStr, _ := json.Marshal(in)
	//	logx.WithContext(l.ctx).Errorf("根据service_id查询grpc表信息失败,参数:%s,异常:%s", reqStr, err.Error())
	//	return nil, err
	//}
	//
	//accessControlDo, err := l.svcCtx.SvcAccessControlModel.FindOne(l.ctx, ServiceId)
	//if err != nil {
	//	reqStr, _ := json.Marshal(in)
	//	logx.WithContext(l.ctx).Errorf("根据service_id查询accesscontrol表信息失败,参数:%s,异常:%s", reqStr, err.Error())
	//	return nil, err
	//}
	//
	//loadBalanceDo, err := l.svcCtx.SvcLoadBalanceModel.FindOne(l.ctx, ServiceId)
	//if err != nil {
	//	reqStr, _ := json.Marshal(in)
	//	logx.WithContext(l.ctx).Errorf("根据service_id查询loadbalance表信息失败,参数:%s,异常:%s", reqStr, err.Error())
	//	return nil, err
	//}
	//detail := &ServiceDetailDo{
	//	Info:          serviceinfo,
	//	HTTPRule:      httpDo,
	//	TCPRule:       tcpDo,
	//	GRPCRule:      grpcDo,
	//	AccessControl: accessControlDo,
	//	LoadBalance:   loadBalanceDo,
	//}

	return &svcclient.ServiceUpdateHttpResp{
		Isok: 1, //ok
	}, nil
}
